package com.huishu.tcm.config;

import com.alibaba.fastjson.JSONObject;
import com.huishu.tcm.vo.ResultVo;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.net.URI;

@RestControllerAdvice(basePackages = {"com.huishu.tcm.controller"})
public class ResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        URI u = request.getURI();
        if(u.getPath().contains("uploadImg")){
            return body;
        }
        if(u.getPath().contains("swagger") || u.getPath().contains("api-docs")){
            return body;
        }
        if (body instanceof ResultVo){
            return body;
        }
        ResultVo resultVo = new ResultVo();
        resultVo.setData(body);

        if(body instanceof String){
            return JSONObject.toJSONString(resultVo);
        }
        return resultVo;
    }
}
